package com.shirley.reactive.ws.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;

@SpringBootApplication
public class SpringReactiveWsClientApplication {

    public static void main(String[] args) throws URISyntaxException, IOException {
        SpringApplication.run(SpringReactiveWsClientApplication.class, args);

        WebSocketClient client = new ReactorNettyWebSocketClient();
        client.execute(
                        URI.create("ws://localhost:8082/ws"),
                        session -> {
                            session.receive()
                                    .map(WebSocketMessage::getPayloadAsText)
                                    .log();
                            return session.send(
                                    // send message to server every 2 seconds.
                                    Flux.interval(Duration.ofSeconds(2))
                                            .take(10)
                                            .map(v -> session.textMessage("Hello " + v)))
                                    .and(session.receive()
                                    .map(WebSocketMessage::getPayloadAsText)
                                    .log());
                        })
                .block(Duration.ofSeconds(10000L));
    }

}
